const {
    getNewToken,
    getNewTicket,
    getQr_ticket,
    getUserInfo,
    getRight,
    getValidateString
} = require("../../utils/WecChat");
let sha1 = require('sha1');
let {ticketObj} = require("../../config/AuthConfig");
const {weChatConfig} = require("../../config/AuthConfig");
const {request} = require("http");
const {getXMLStr, getJsData, getObjData} = require("../../wechat/utils");
const {generateToken} = require("../../utils/JWT");
// 有效期
let enableTimestamp = 0
// 过渡时间 提早5分钟，重新获取token
let transitionTime = 5 * 60 * 1000;
//这个是natapp映射内网出来的
const serverUrl = 'https://xuxiao888.com/';
// 那些关注的人
let subscribe_arr = [];
// 获取openId
// scope为snsapi_base
var redirect_uri = `${serverUrl}/html/`
var snsapi_base_Url = `https://open.weixin.qq.com/connect/oauth2/authorize?
          appid=${weChatConfig.appId}
          &redirect_uri=${encodeURIComponent(redirect_uri)}
          &response_type=code
          &scope=snsapi_base
          &state=123#wechat_redirect`;

let access_token_obj = {
    "access_token": "86_s4Dj-vM9TQKgz0AA0fdSodXqY-M5wqv5rMOUzyhXJaUjyWKec3H84llIHytYdjtJn3Wri83Fr904U0Ow6VZ4jJafCO0dViggCzB9iB6p5Ejx7KlVdi5F4etbyz0ODRcADAKZN",
    "expires_in": 7200
}
exports.auth = async (req, res, next) => {
    console.log(':根路径，有信息 ：', req.body, req.query);
    // 解构参数
    let {signature, echostr, timestamp, nonce} = req.query;
    let relStr = getValidateString(req)
    // 然后和signature比较，是否一致
    if (relStr == signature) {
        console.log('验证通过-2--');
        // res.send(true)
        res.send(echostr)
    } else {
        console.log('验证不通过-1--');
        res.send(false)
    }
}
exports.initWeChatParams = async (req, res, next) => {
    // 现在
    const nowTimeStamp = Date.now();
    // 1.判断当前的有效期，是否有效
    if ((enableTimestamp - transitionTime) < nowTimeStamp) {
        console.log('过期了：重新请求---');
        // 如果是在过渡时间内了，要重新请求
        let rel = await getNewToken()
        // 根据获取到的token，继续获取ticket
        console.log('rel:', rel, 56);

        access_token_obj.access_token = rel.access_token; // 假设 rel 对象中有 token 属性
        access_token_obj.expires_in = rel.expires_in; // 如果有过期时间也更新

        console.log('access_token_obj:', access_token_obj, 60)
        ticketObj = await getNewTicket(access_token_obj.access_token);
        enableTimestamp += nowTimeStamp + ticketObj.expires_in * 1000;
        console.log('ticketObj:', ticketObj);
    } else {
        console.log('未过期--使用旧的1');
    }
    const obj2 = {
        noncestr: (Math.random() + '').split('.')[1],
        jsapi_ticket: ticketObj.ticket,
        timestamp: nowTimeStamp,
        url: `${serverUrl}/html/`
    }
    let js_arr = [
        `jsapi_ticket=${obj2.jsapi_ticket}`,
        `noncestr=${obj2.noncestr}`,
        `timestamp=${obj2.timestamp}`,
        `url=${obj2.url}`
    ];
    let js_str = js_arr.sort().join('&')
    console.log('js_str', js_str);
    let signature = sha1(js_str);
    console.log('signature', signature);
    const config_obj = {
        appId: weChatConfig.appId, // 必填，公众号的唯一标识
        timestamp: nowTimeStamp, // 必填，生成签名的时间戳
        nonceStr: obj2.noncestr, // 必填，生成签名的随机串
        signature,// 必填，签名
    }
    res.send(config_obj)
}

exports.getQrCode = async (req, res, next) => {
    console.log('数据getQrCode:', req.body);
    let data = req.body
    let ticketObj = await getQr_ticket(data, access_token_obj.access_token)
    res.send(ticketObj)
}
exports.subscribe = (req, res, next) => {
    console.log('数据code1:', req.body);
    let {ticket, myId} = req.body;

    // 方法1：ticket可以验证
    let index = subscribe_arr.findIndex(item => item == ticket);

    // 方法2：myId也可以验证
    index = subscribe_arr.findIndex(item => {
        if (item === myId) {
            return true;
        } else if (String(item).includes('_') && String(item).split('_')[1] === myId) {
            // 第一次关注会返回这个 EventKey: 'qrscene_619122'
            return true;
        }
    });
    console.log('index', index);
    let hasOne = true;
    let token
    if (index == -1) {
        hasOne = false;
    } else {
        console.log('验证通过，登录成功------------------');

        token = generateToken({id: myId, username: 'wechat', loginDevice: 'wechat'})
    }
    res.send({
        status: 0,
        data: hasOne,
        token: token ? token : ""
    })
}

exports.getCode = (req, res, next) => {
    console.log('code数据:', req.body);
    const {code} = req.body;
    let url = `https://api.weixin.qq.com/sns/oauth2/access_token?appid=${weChatConfig.appId}&secret=${weChatConfig.appSecret}&code=${code}&grant_type=authorization_code`
    return new Promise((resolve, reject) => {
        request(url, async function (error, response, body) {
            if (!error) {
                console.log('openId_成功11：error, response, body', typeof body, body)
                // resolve(JSON.parse(body))\
                let userInfo = await getUserInfo(JSON.parse(body))
                res.send(userInfo)

            } else {
                console.log('error：', error)
                // reject(error)
                res.send(JSON.parse(error))
            }
        });
    })
}

exports.getUserInfo = (req, res, next) => {
    console.log('数据code :', req.body);
    const {code} = req.body
    return new Promise((resolve, reject) => {
        const server = 'http://qiaolianyun.viphk.91tunnel.com/wxsss/OpenIDss'
        // const server= 'http://qiaolianyun.viphk.91tunnel.com/servlet/getUserInfo';
        const other_server = `${server}?code=${code}`
        request(other_server, function (error, response, body) {
            if (!error) {
                console.log('getRight_成功11：error, response, body', typeof body, body)
                // resolve(JSON.parse(body))\
                res.send(JSON.parse(body))
            } else {
                console.log('error：', error)
                // reject(error)
                res.send(JSON.parse(error))
            }
        });
    })
}

exports.getRight = async (req, res, next) => {
    let rel = await getRight(snsapi_base_Url);
    console.log('object');
    res.send(rel)
}
exports.HandlePostMsg = async (req, res, next) => {
    console.log('post-home:', req.query);
    let {signature, echostr, timestamp, nonce} = req.query;
    let relStr = getValidateString(req)
    if (relStr == signature) {
        console.log('信息来自微信服务器--');
        // 提取信息
        let xmlData = await getXMLStr(req);
        console.log('xmlData:', xmlData);
        // 通过工具解析xml数据
        let jsData = await getJsData(xmlData)
        console.log('jsData:', jsData);
        // 再次优化数据
        let msgObj = getObjData(jsData.xml)
        console.log('msgObj:', msgObj);
        subscribe_arr.push(msgObj.Ticket)
        subscribe_arr.push(msgObj.EventKey)
        // 如果长度超过100，登录人数过多时
        if (subscribe_arr.length > 100) {
            let start = subscribe_arr.length - 100;
            subscribe_arr = subscribe_arr.slice(start)
        }
        // 回复信息给 微信服务器
        let content = ''
        if (msgObj.MsgType == 'text') {
            if (msgObj.Content == 1) {
                content = '努力吧！'
            } else if (msgObj.Content == 2) {
                content = '再坚持一会，就成功了'
            } else if (msgObj.Content.includes('爱')) {
                content = '爱你一万年！'
            } else {
                content = '谢谢！'
            }
        } else if (msgObj.MsgType == 'event') {
            content = 'event事件'
            if (msgObj.Event == 'SCAN') {
                content = '好家伙，手机扫码'
            } else if (msgObj.Event == 'subscribe') {
                content = '好家伙，欢迎您的关注！'
            }
            if (msgObj.Event == 'unsubscribe') {
                content = '好家伙，你居然敢取笑关注？'
            }
        } else {
            content = '其他信息来源！'
        }
        // 根据来时的信息格式，重组返回。(注意中间不能有空格)
        let msgStr = `<xml>
      <ToUserName><![CDATA[${msgObj.FromUserName}]]></ToUserName>
      <FromUserName><![CDATA[${msgObj.ToUserName}]]></FromUserName>
      <CreateTime>${Date.now()}</CreateTime>
      <MsgType><![CDATA[text]]></MsgType>
      <Content><![CDATA[${content}]]></Content>
    </xml>`
        res.send(msgStr)
    } else {
        console.log('信息来历不明--');
    }
}